package org.easylookandfeel.adapter;

import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JComboBox;
import javax.swing.UIManager.LookAndFeelInfo;

/**
 * A built-in implementation of {@link LookAndFeelAdapter} interface. It builds
 * a look and feel selection on a given {@link JComboBox}. The client
 * application must only pass a reference to {@link JComboBox} where look and
 * feel options will be placed in.
 * 
 * @author pcmnac@gmail.com
 * 
 */
public class ComboBoxLookAndFeelAdapter extends AbstractLookAndFeelAdapter {

  /**
   * {@link JComboBox} where look and feel options will be placed in.
   */
  private JComboBox cboLookAndFeels;

  /**
   * Flag to avoid infinite loop.
   */
  private boolean waitingInternal;

  /**
   * Constructor.
   * 
   * @param comboBox
   *          The ComboBox where look and feel options will be placed.
   */
  public ComboBoxLookAndFeelAdapter(JComboBox comboBox) {
    this.cboLookAndFeels = comboBox;
  }

  /**
   * @see org.easylookandfeel.adapter.LookAndFeelAdapter#handleLookAndFeelChanged(int)
   */
  public void handleLookAndFeelChanged(int lookAndFeelIndex) {
    waitingInternal = true;
    cboLookAndFeels.setSelectedIndex(lookAndFeelIndex);
  }

  /**
   * @see org.easylookandfeel.adapter.LookAndFeelAdapter#initializeLookAndFeel(javax.swing.UIManager.LookAndFeelInfo[])
   */
  public void initializeLookAndFeel(LookAndFeelInfo[] looks) {
    cboLookAndFeels.removeAllItems();
    if (looks.length > 0) {
      for (int i = 0; i < looks.length; i++) {
        cboLookAndFeels.addItem(looks[i].getName());
      }
      cboLookAndFeels.addItemListener(new ItemListener() {

        /**
         * @see java.awt.event.ItemListener#itemStateChanged(java.awt.event.ItemEvent)
         */
        public void itemStateChanged(ItemEvent e) {
          if (!waitingInternal) {
            getManager().changeLookAndFeel(cboLookAndFeels.getSelectedIndex());
          } else {
            waitingInternal = false;
          }
        }
      });
    }

  }
}
